package edu.hawaii.halealohacli;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Scanner;
import org.wattdepot.client.WattDepotClient;

/**
 * Processor: Takes user command input from the main method and compares it to available commands.
 * This calls command every time one is run, so the list of baselines is stored here.
 * 
 * @author John MacMillan
 * @author Mitchell Kupfer
 * @author Bryson Hori
 * @author Chris Fang
 * @author Jordan Do
 * 
 */
public class Processor {
  Baselist baseList = new Baselist();
  /**
   * Generic Constructor.
   */
  public Processor() {
    // empty constructor
  }

  /**
   * Gets the user input from the main method.
   * 
   * @param input a single string from main.
   * @param client the WattDepot client.
   */
  public void parseInput(String input, WattDepotClient client) {

    try {
      // creates a scanner to cut up input by white space
      Scanner scan = new Scanner(input).useDelimiter("\\s");

      AbstractList<String> inputs = new ArrayList<String>();

      // adds each input to an array
      while (scan.hasNext()) {
        inputs.add(scan.next());
      }

      // checks the validity of the command and number of arguments
      checkValidity(inputs.get(0), inputs, client);
    }

    catch (Exception e) {
      System.out.println("Bad input please try again or type \"help\" ");

    }

  }

  /**
   * Validate the input through comparison with the tree.
   * 
   * @param command the users command they want to execute
   * @param strings a variable number of additional string arguments.
   * @param client the WattDepot client.
   */
  protected void checkValidity(String command,
      AbstractList<String> strings, WattDepotClient client) {

    // =============== debugging code ================================
    // System.out.println("\ncheckValidity called");

    // for (String s : strings) {
    // System.out.println("element in input: " + s);
    // }

    // System.out.println("total length: " + strings.size());
    // ============== stop debugging code =================================

    // creates a tree with a static number of commands
    Tree tree = new Tree();
    tree.buildTree();

    // checks to see if users command is in the tree
    if (!tree.contains(command)) {
      System.out.print("Invalid Command\n");
      return;
    }

    // checks that the number of arguments for the command are correct.
    if (!tree.checkInput(command, strings)) {
      System.out.print("Invalid Number of Inputs\n");
      return;
    }

    Command commands = new Command(strings, client, baseList);

    if (!commands.executeCommand()) {
      System.out.println("Command was not processed, please check for correct arguments");
    }
  }

}
